package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.ruoyi.ai.domain.SysAiPrompt;
import com.ruoyi.ai.domain.SysAiQuest;
import com.ruoyi.ai.domain.SysAiTasks;
import com.ruoyi.ai.mapper.SysAiPromptMapper;
import com.ruoyi.ai.mapper.SysAiQuestMapper;
import com.ruoyi.ai.mapper.SysAiTasksMapper;
import com.ruoyi.ai.service.ISysAiPromptService;
import com.ruoyi.ai.service.impl.SysAiPromptServiceImpl;
import com.ruoyi.common.core.domain.entity.SysAITask;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.BigModelNew;
import com.ruoyi.common.utils.BigModelWeb;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.qywx.domain.SysQywxChatdata;
import com.ruoyi.qywx.mapper.SysQywxChatdataMapper;
import com.ruoyi.qywx.service.ISysQywxChatdataService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysAIService;

import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Service
public class SysAIServiceImpl implements ISysAIService {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    //@Autowired
    //private SysAiPromptMapper sysAiPromptMapper;

    @Resource
    @Value(value = "${qywx.corpID}")
    private String corpID;

    @Resource
    @Value(value = "${qywx.secret}")
    private String secret;

    @Resource
    @Value(value = "${qywx.qywxURL}")
    private String qywxURL;

    @Resource
    @Value(value = "${qywx.agentId}")
    private String agentId;

    @Autowired
    private ISysQywxChatdataService sysQywxChatdataService;

    @Resource
    private SysQywxChatdataMapper sysQywxChatdataMapper;
    @Resource
    private SysAiPromptMapper sysAiPromptMapper;
    @Resource
    private SysAiTasksMapper sysAiTasksMapper;
    @Resource
    private SysAiQuestMapper sysAiQuestMapper;
    @Resource
    private SysUserMapper userMapper;

    public static SysAIServiceImpl sysAIServiceImpl;

    public static Map<String, String> roomNameList = new HashMap<>();
    public static Map<String, String> userNameList = new HashMap<>();

    //msg时间内可合并
    public static long delayTimestamp = 120000;//120秒 120000毫秒

    @PostConstruct
    public void init(){
        sysAIServiceImpl=this;
        sysAIServiceImpl.sysQywxChatdataMapper=sysQywxChatdataMapper;
        sysAIServiceImpl.sysAiPromptMapper=sysAiPromptMapper;
        sysAIServiceImpl.sysAiTasksMapper=sysAiTasksMapper;
        sysAIServiceImpl.userMapper=userMapper;
        sysAIServiceImpl.sysAiQuestMapper=sysAiQuestMapper;

        sysAIServiceImpl.corpID=corpID;
        sysAIServiceImpl.secret=secret;
        sysAIServiceImpl.qywxURL=qywxURL;
        sysAIServiceImpl.agentId=agentId;


    }

    //自然语言 分析提取任务内容
    @Override
    public List<SysAiTasks> taskAnalysis(String content) throws Exception {
        return SysAIServiceImpl.taskAnalysisContent(content, (new Date()).getTime());
    }


    //如果超过6000字 分开分析  我擦
    public static List<SysAiTasks> taskSplitContent(String content) throws Exception {
        List<SysAiTasks> list = new ArrayList<>();

        String [] contentList = content.split("\n");
        String newContent = "";
        for(int i=0;i<contentList.length;i++){
            newContent = newContent + contentList[i] + "\n";
            if(newContent.length() > 4000) {
                List<SysAiTasks> tempList = SysAIServiceImpl.taskSplitContentStep2(newContent);
                list.addAll(tempList);
                newContent = "";
            }
        }
        if(newContent.length()>2) {
            List<SysAiTasks> tempList = SysAIServiceImpl.taskSplitContentStep2(newContent);
            list.addAll(tempList);
        }
        return list;
    }

    public static List<SysAiTasks> taskSplitContentStep2(String content) throws Exception {

        //查找ai扩展问题
        List<SysAiQuest> questList = sysAIServiceImpl.sysAiQuestMapper.selectSysAiQuestList(new SysAiQuest());
        String quest = "";
        //组合问题
        for(SysAiQuest sysAiQuest:questList){
            quest = quest + sysAiQuest.getQuestType() + "、";
        }

        log.info("==========taskSplitContent start==========");
        List<SysAiTasks> list = new ArrayList<>();
        content = content+" 。$。$$$  首先   不要给我任何示例内容！！不要拿 张三 王五 李四给我举例！！！\n" +
                "然后 从“$$$”之前的内容分别提取(如果是多组内容 就提取多组)：\n" +
                "归纳成一句话，\n" +
                "被归纳的文字原文，\n" +
                "内容类型(从以下类型中选取：  "+quest+"  如果无法分辨类型  则返回  无法分类 )\n" +
                "只以json表格方式罗列给我。\n" +
                "如果提取不到内容 就直接告诉我“提取失败”。";
        log.info("==========content==========");
        log.info(content);
        String result = BigModelWeb.chat(content);
        log.info("==========result==========");
        log.info(result);
        try {
            JSONArray jsonArray = JSONArray.parseArray(result);
            //JSONObject jsonObject = JSONObject.parseObject(result);
            log.info("==========jsonArray==========");
            log.info(jsonArray.toJSONString());
            //log.info(jsonObject.toJSONString());

            int i = 1;
            for (Object jsonObject : jsonArray) {
                JSONObject jObject = (JSONObject) jsonObject;
                log.info(JSONObject.toJSONString(jObject));

                SysAiTasks sysAITask = new SysAiTasks();

                sysAITask.setTaskOrignalJson(JSONObject.toJSONString(jObject));
                //sysAITask.setId(i);
                sysAITask.setTaskMemo(jObject.getString("归纳"));
                sysAITask.setTaskDetail(jObject.getString("原文"));
                if(StringUtils.isEmpty(sysAITask.getTaskDetail()) || sysAITask.getTaskDetail()==null || sysAITask.getTaskDetail().equals("")){
                    sysAITask.setTaskDetail(jObject.getString("被归纳的文字原文"));
                }

                list.add(sysAITask);
                i++;
            }
        }catch (Exception e1){

            try {
                JSONObject jObject = JSONObject.parseObject(result);
                log.info(JSONObject.toJSONString(jObject));

                SysAiTasks sysAITask = new SysAiTasks();
                //sysAITask.setId(1);
                sysAITask.setTaskMemo(jObject.getString("归纳"));
                sysAITask.setTaskDetail(jObject.getString("原文"));
                if(StringUtils.isEmpty(sysAITask.getTaskDetail()) || sysAITask.getTaskDetail()==null || sysAITask.getTaskDetail().equals("")){
                    sysAITask.setTaskDetail(jObject.getString("被归纳的文字原文"));
                }

                list.add(sysAITask);
            }catch (Exception ex2){
                log.info("==========big error big error  ===============");
                log.info(result);
                log.info(ex2.toString());
            }
        }

        return list;
    }

    //额外ai扩展问题
    public static SysAiTasks taskAnalysisQuest(String quest_Type, String content, List<SysAiQuest> questList) throws Exception {
        SysAiTasks sysAiTasks = new SysAiTasks();


        for(SysAiQuest sysAiQuest:questList){
            if(!StringUtils.isEmpty(sysAiQuest.getQuestType()) && sysAiQuest.getQuestType().equals(quest_Type)){

                content = content+" 。$$$  首先   不要给我任何示例内容！！不要拿 张三 王五 李四给我举例！！！\n" +
                        "然后 对“$$$”之前的内容分别提取：\n";
                content = content+sysAiQuest.getQuest1()+ "，\n";
                content = content+sysAiQuest.getQuest2()+ "，\n";
                content = content+sysAiQuest.getQuest3()+ "，\n";
                content = content+"只以json表格方式罗列给我。\n" +
                        "如果提取不到内容 就直接告诉我“提取失败”。\n";


                String result = BigModelWeb.chat(content);

                try {
                    JSONObject jObject = JSONObject.parseObject(result);
                    int i=0;
                    for (String key : jObject.keySet()) {
                        if(i==0) {
                            sysAiTasks.setTaskProblem(jObject.getString(key));
                        }
                        if(i==1) {
                            sysAiTasks.setTaskResult(jObject.getString(key));
                        }
                        if(i==2) {
                            sysAiTasks.setTaskSolution(jObject.getString(key));
                        }
                        i++;
                    }
                }catch (Exception ex2){
                    log.info("=======taskAnalysisQuest===big error big error  ===============");
                    log.info(result);
                    log.info(ex2.toString());
                }

                break;
            }
        }

        return sysAiTasks;
    }

    public static List<SysAiTasks> taskAnalysisContent(String content, long msgtimestamp) throws Exception {
        String tmpContent = content;
        log.info("==========taskAnalysis start==========");
        List<SysAiTasks> list = new ArrayList<>();


        Timestamp timestamp = new Timestamp(msgtimestamp);
        Date currentDate = new Date(timestamp.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd EEE");
        String formattedDate = sdf.format(currentDate);

        //查询提示词配置
        //SysAiPromptServiceImpl sysAiPromptService = new SysAiPromptServiceImpl();
        SysAiPrompt sysAiPrompt = new SysAiPrompt();
        sysAiPrompt.setIsUse("Y");
        List<SysAiPrompt> sysAiPromptList = sysAIServiceImpl.sysAiPromptMapper.selectSysAiPromptList(sysAiPrompt);
        log.info("==========sysAiPromptList==========" + JSON.toJSONString(sysAiPromptList));

        /*
        content = content+" 。$$$ 从“$$$”之前的内容分别提取(如果是多组内容 就提取多组)：\n" +
                "日期(如果没有日期 显示 无， 如果有日期则从今天 "+formattedDate+" 开始计算)， \n" +
                "时间（格式 时:分:秒），如无显示无，\n" +
                "关联人是谁，\n" +
                "需要做什么，\n" +
                "归类到 有日期与具体时间，有日期没具体时间，\n" +
                "是否是会议（用 是 或者 否），\n" +
                "是否包含关键词（从 金典、蒙牛、伊利 这些词中去匹配关键词），\n" +
                "关键词，\n" +
                "概括内容，\n" +
                "只以json表格方式罗列给我。\n" +
                "如果提取不到内容或信息不详 就直接告诉我“提取失败”， 不要给我任何示例内容！";
                */

        //查找ai扩展问题
        List<SysAiQuest> questList = sysAIServiceImpl.sysAiQuestMapper.selectSysAiQuestList(new SysAiQuest());
        String quest = "";
        //组合问题
        for(SysAiQuest sysAiQuest:questList){
            quest = quest + sysAiQuest.getQuestType() + "，";
        }

        content = content + " 。" + sysAiPromptList.get(0).getPrompt().replace("{today}", formattedDate).replace("{quest}", quest);

        //log.info("==========prompt==========");
        //log.info(content);
        log.info("==========content==========");
        log.info(content);
        String result = BigModelWeb.chat(content);
        log.info("==========result==========");
        log.info(result);

        try {
            JSONArray jsonArray = JSONArray.parseArray(result);
            //JSONObject jsonObject = JSONObject.parseObject(result);
            log.info("==========jsonArray==========");
            log.info(jsonArray.toJSONString());
            //log.info(jsonObject.toJSONString());

            int i = 1;
            for (Object jsonObject : jsonArray) {
                JSONObject jObject = (JSONObject) jsonObject;
                log.info(JSONObject.toJSONString(jObject));

                SysAiTasks sysAITask = new SysAiTasks();

                sysAITask.setTaskOrignalJson(JSONObject.toJSONString(jObject));
                //sysAITask.setId(i);
                sysAITask.setTaskTime(jObject.getString("时间"));
                sysAITask.setTaskMemo(jObject.getString("归纳成一句话"));
                if(sysAITask.getTaskMemo()==null){
                    sysAITask.setTaskMemo(jObject.getString("一句话归纳"));
                }
                if(sysAITask.getTaskMemo()==null){
                    sysAITask.setTaskMemo(jObject.getString("精简的话"));
                }
                if(sysAITask.getTaskMemo()==null){
                    sysAITask.setTaskMemo(jObject.getString("归纳成一句精简的话"));
                }
                //List<String> userlist = new ArrayList<>();
                String userlist = "";
                try {
                    JSONArray userJSONArray = (JSONArray) jObject.get("关联人");
                    String userStr = "";
                    for (Object uObject : userJSONArray) {
                        //userlist.add((String) uObject);
                        userStr = userStr + " " + (String) uObject;
                    }
                    userlist = (userStr);
                } catch (Exception ex) {
                    userlist = jObject.getString("关联人");
                }

                sysAITask.setTaskUserlist(userlist);

                String strIsMeeting = jObject.getString("是否是会议");
                sysAITask.setIsMeeting(0L);
                if("是".equals(strIsMeeting)){
                    sysAITask.setIsMeeting(1L);
                }

                String strIsKey = jObject.getString("是否包含关键词");
                if("是".equals(strIsKey)){
                    sysAITask.setTaskKeyword(jObject.getString("关键词"));
                }

                sysAITask.setTaskDetail(jObject.getString("拆分为若干个行动项"));
                try {
                    sysAITask.setTaskActions(jObject.getString("内容类型"));
                }catch (Exception ex){
                    log.info("==========内容类型error-error-rror==========");
                    log.info(jObject.toJSONString());
                }
                sysAITask.setTaskAddress(jObject.getString("地点"));
                sysAITask.setTaskIsProblem(jObject.getString("是否有问题"));
                sysAITask.setTaskProblem(jObject.getString("问题是什么"));
                sysAITask.setTaskIsResult(jObject.getString("是否有结论"));
                sysAITask.setTaskResult(jObject.getString("结论是什么"));
                sysAITask.setTaskIsSolution(jObject.getString("是否有解决方案"));
                sysAITask.setTaskSolution(jObject.getString("解决方案是什么"));
                sysAITask.setTaskRes(jObject.getString("对话涉及到哪些资源"));
                sysAITask.setTaskTerms(jObject.getString("对话涉及到哪些术语"));
                sysAITask.setTaskTargets(jObject.getString("对话涉及到哪些指标"));

                //AI扩展问题
                SysAiTasks tempTask = SysAIServiceImpl.taskAnalysisQuest(sysAITask.getTaskActions(), tmpContent, questList);
                //三大问题
                sysAITask.setTaskProblem(tempTask.getTaskProblem());
                sysAITask.setTaskResult(tempTask.getTaskResult());
                sysAITask.setTaskSolution(tempTask.getTaskSolution());

                try {
                    sysAITask.setTaskDate((jObject.get("日期").toString().replace("T"," ")));
                }catch (Exception ex3){
                    log.info(ex3.toString());

                    try {
                        sysAITask.setTaskDate((jObject.get("日期").toString().replace("T"," ")));
                    }catch (Exception ex4) {
                        log.info(ex4.toString());
                        try {
                            sysAITask.setTaskDate((jObject.get("日期").toString()));
                        }catch (Exception ex5) {
                            try {
                                sysAITask.setTaskDate((jObject.get("日期").toString()));
                            }catch (Exception ex6) {

                            }
                        }
                    }
                }
                list.add(sysAITask);
                i++;
            }
        }catch (Exception e1){

            try {
                JSONObject jObject = JSONObject.parseObject(result);
                log.info(JSONObject.toJSONString(jObject));

                SysAiTasks sysAITask = new SysAiTasks();
                //sysAITask.setId(1);
                sysAITask.setTaskTime(jObject.getString("时间"));
                sysAITask.setTaskMemo(jObject.getString("归纳成一句话"));
                if (sysAITask.getTaskMemo() == null) {
                    sysAITask.setTaskMemo(jObject.getString("一句话归纳"));
                }
                if(sysAITask.getTaskMemo()==null){
                    sysAITask.setTaskMemo(jObject.getString("精简的话"));
                }
                if(sysAITask.getTaskMemo()==null){
                    sysAITask.setTaskMemo(jObject.getString("归纳成一句精简的话"));
                }
                //List<String> userlist = new ArrayList<>();
                String userlist = "";
                try {
                    JSONArray userJSONArray = (JSONArray) jObject.get("关联人");
                    String userStr = "";
                    for (Object uObject : userJSONArray) {
                        //userlist.add((String) uObject);
                        userStr = userStr + " " + (String) uObject;
                    }
                    userlist = (userStr);
                } catch (Exception ex) {
                    userlist = jObject.getString("关联人");
                }

                sysAITask.setTaskUserlist(userlist);

                String strIsMeeting = jObject.getString("是否是会议");
                sysAITask.setIsMeeting(0L);
                if ("是".equals(strIsMeeting)) {
                    sysAITask.setIsMeeting(1L);
                }

                String strIsKey = jObject.getString("是否包含关键词");
                if ("是".equals(strIsKey)) {
                    sysAITask.setTaskKeyword(jObject.getString("关键词"));
                }

                sysAITask.setTaskDetail(jObject.getString("拆分为若干个行动项"));
                try {
                    sysAITask.setTaskActions(jObject.getString("内容类型"));
                }catch (Exception ex){
                    log.info("==========内容类型error-error-rror==========");
                    log.info(jObject.toJSONString());
                }                sysAITask.setTaskAddress(jObject.getString("地点"));
                sysAITask.setTaskIsProblem(jObject.getString("是否有问题"));
                sysAITask.setTaskProblem(jObject.getString("问题是什么"));
                sysAITask.setTaskIsResult(jObject.getString("是否有结论"));
                sysAITask.setTaskResult(jObject.getString("结论是什么"));
                sysAITask.setTaskIsSolution(jObject.getString("是否有解决方案"));
                sysAITask.setTaskSolution(jObject.getString("解决方案是什么"));
                sysAITask.setTaskRes(jObject.getString("对话涉及到哪些资源"));
                sysAITask.setTaskTerms(jObject.getString("对话涉及到哪些术语"));
                sysAITask.setTaskTargets(jObject.getString("对话涉及到哪些指标"));

                //AI扩展问题
                SysAiTasks tempTask = SysAIServiceImpl.taskAnalysisQuest(sysAITask.getTaskActions(), tmpContent, questList);
                //三大问题
                sysAITask.setTaskProblem(tempTask.getTaskProblem());
                sysAITask.setTaskResult(tempTask.getTaskResult());
                sysAITask.setTaskSolution(tempTask.getTaskSolution());

                try {
                    sysAITask.setTaskDate((jObject.get("日期").toString().replace("T", " ")));
                } catch (Exception ex3) {
                    log.info(ex3.toString());

                    try {
                        sysAITask.setTaskDate((jObject.get("日期").toString().replace("T", " ")));
                    } catch (Exception ex4) {
                        log.info(ex4.toString());
                        try {
                            sysAITask.setTaskDate((jObject.get("日期").toString()));
                        } catch (Exception ex5) {
                            try {
                                sysAITask.setTaskDate((jObject.get("日期").toString()));
                            } catch (Exception ex6) {

                            }
                        }
                    }
                }

                list.add(sysAITask);
            }catch (Exception ex2){
                log.info("==========big error big error  ===============");
                log.info(result);
                log.info(ex2.toString());
            }
        }

        //sysAITask.setTaskmemo(result);
        return list;
    }


    //自然语言 分析组合任务内容
    public static void taskListHandled() throws IOException {
        SysQywxChatdata sysQywxChatdata = new SysQywxChatdata();
        sysQywxChatdata.setIsHandled(0L);
        List<SysQywxChatdata> list = sysAIServiceImpl.sysQywxChatdataMapper.selectSysQywxChatdataList(sysQywxChatdata);
        list.sort(Comparator.comparing(SysQywxChatdata::getSeq));//升序  从日期早的 聊天记录开始
        log.info("==========taskListHandled===========");
        //log.info(JSON.toJSONString(list));


        //开始组合内容
        List<QYWXChatUni> QYWXChatUniList = new ArrayList<>();

        for (SysQywxChatdata tmpChatdata:list) {
            //先检验 是否可以合并到旧列表中
            log.info(tmpChatdata.getSeq().toString());
            //JSONObject JSONObject = JSON.parseObject(tmpChatdata.getDecryptChatMsg());

            if(SysAIServiceImpl.checkAndInsert(QYWXChatUniList, tmpChatdata)){
                //成功加入列表
            }else{
                //失败
            }

        }

        //开始批量处理
        //1 第一步 先清理掉 距今不足120秒的  因为无需处理
        long nowtime = (new Date()).getTime();
        for(int i=0;i<QYWXChatUniList.size();i++){
            long lastMsgtime = QYWXChatUniList.get(i).getLastMsgtime();
            if(Math.abs(nowtime - lastMsgtime) <= SysAIServiceImpl.delayTimestamp){
                //时间不到 删  等下一轮吧
                QYWXChatUniList.get(i).setIsdel(true);
                log.info("还未到两分钟，清理掉： "+i+" , "+QYWXChatUniList.get(i).getAllMsg());
            }else{
                QYWXChatUniList.get(i).setIsdel(false);
            }
        }

        //2 第二步 开始语音语义的处理
        for(int s=0;s<QYWXChatUniList.size();s++){
            QYWXChatUni tmpChatUni = QYWXChatUniList.get(s);
            log.info("handle QYWXChatUniList " + s + "/" + QYWXChatUniList.size());

            if(!tmpChatUni.getIsdel()) {
                //处理语义
                //开始大模型分析...
                try {
                    int i = 0;
                    List<SysAiTasks> sysAiTasksList = SysAIServiceImpl.taskAnalysisContent(tmpChatUni.getAllMsg(), tmpChatUni.getLastMsgtime());
                    System.out.println("from:" + tmpChatUni.getFrom());
                    System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTasksList));
                    for (int x = 0; x < sysAiTasksList.size(); x++) {
                        //sysAiTasksList.forEach(task -> {
                        SysAiTasks task = sysAiTasksList.get(x);
                        //if(!"".equals(task.getTaskMemo()) && !"无".equals(task.getTaskMemo()) && task.getTaskMemo()!=null){
                        //    if(!"".equals(task.getTaskDate()) && !"无".equals(task.getTaskDate()) && task.getTaskDate()!=null){
                        task.setTaskCreator(tmpChatUni.getFrom());
                        task.setRoomid(tmpChatUni.getRoomid());
                        task.setRoomName(tmpChatUni.getRoomName());
                        task.setMsgtime(tmpChatUni.getLastMsgtime());
                        task.setOrignalContent(tmpChatUni.getAllMsg());
                        task.setOrignalMsg(tmpChatUni.getQywxChatlist().get(0).getDecryptChatMsg());//暂时只存第一个 反正用来搜索发送人 和 收信人

                        System.out.println("task=======" + JSON.toJSONString(task));
                        sysAIServiceImpl.sysAiTasksMapper.insertSysAiTasks(task);
                        try {
                            SysAIServiceImpl.addQYWXSchedulePre(task);//加入日历
                        }catch (Exception ex){
                            System.out.println("addQYWXSchedulePre=error======" + JSON.toJSONString(ex));
                        }

                        i = i + 1;
                            /*    }else{
                                    System.out.println("SysAiTasks err 没有具体日期 跳过");
                                }
                            }else{
                                System.out.println("SysAiTasks err 没有任务内容 跳过");
                            }*/
                        //});
                    }
                    System.out.println("AtomicInteger i 成功插入任务数: " + i);
                    if (i <= 0) {
                        System.out.println("一个都没录入重来....... " + i);
                        //一个都没录入重来
                        sysAiTasksList = SysAIServiceImpl.taskAnalysisContent(tmpChatUni.getAllMsg(), tmpChatUni.getLastMsgtime());
                        System.out.println("from:" + tmpChatUni.getFrom());
                        System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTasksList));
                        for (int x = 0; x < sysAiTasksList.size(); x++) {
                            //sysAiTasksList.forEach(task -> {
                            SysAiTasks task = sysAiTasksList.get(x);
                            //if(!"".equals(task.getTaskMemo()) && !"无".equals(task.getTaskMemo()) && task.getTaskMemo()!=null){
                            //if(!"".equals(task.getTaskDate()) && !"无".equals(task.getTaskDate()) && task.getTaskDate()!=null){

                            task.setTaskCreator(tmpChatUni.getFrom());
                            task.setRoomid(tmpChatUni.getRoomid());
                            task.setRoomName(tmpChatUni.getRoomName());
                            task.setMsgtime(tmpChatUni.getLastMsgtime());
                            task.setOrignalContent(tmpChatUni.getAllMsg());
                            task.setOrignalMsg(tmpChatUni.getQywxChatlist().get(0).getDecryptChatMsg());//暂时只存第一个 反正用来搜索发送人 和 收信人

                            System.out.println("task=======" + JSON.toJSONString(task));
                            sysAIServiceImpl.sysAiTasksMapper.insertSysAiTasks(task);
                            try {
                                SysAIServiceImpl.addQYWXSchedulePre(task);//加入日历
                            }catch (Exception ex){
                                System.out.println("addQYWXSchedulePre=error======" + JSON.toJSONString(ex));
                            }
                                /*    }else{
                                        System.out.println("SysAiTasks err 没有具体日期 跳过");
                                    }
                                }else{
                                    System.out.println("SysAiTasks err 没有任务内容 跳过");
                                }*/
                            //});
                        }
                        System.out.println("AtomicInteger i 成功插入任务数: " + i);
                    }

                } catch (Exception ex) {
                    System.out.println("taskAnalysis err " + ex.toString());
                }

                //标记已处理.......
                for (SysQywxChatdata tmpQywxChatdata:tmpChatUni.getQywxChatlist()) {
                    SysQywxChatdata updateChatdata = new SysQywxChatdata();
                    updateChatdata.setSeq(tmpQywxChatdata.getSeq());
                    updateChatdata.setIsHandled(1L);

                    sysAIServiceImpl.sysQywxChatdataMapper.updateSysQywxChatdata(updateChatdata);
                }
            }

        }
    }

    //实际使用的=================
    //自然语言 分析组合任务内容，将全天信息 整合处理
    public static void taskListMergeHandled(Date theDate) throws Exception {
        //先用户列表  按照用户 总结当天内容

        //0.重整聊天数据 存储消息时间 ...ok
        //1.取得最新 seq...ok
        //2.先取得用户列表...ok
        //3.根据绑定账户名 过滤 seq之前数据 并 根据 绑定账户 筛选数据...ok
        //4.所筛选记录 根据群号按天组装数据。  再根据按天删除旧数据 重新插入新数据 （编辑过的除外）...ok
        //5.根据所收集的分组数据 组合询问AI，并抽取分组文字 并再次询问，形成任务 ...ok
        //6.通知用户当日最新信息  两个按钮...ok
        //7.给到列表 可查看 可编辑 可按照群过滤

        //1. 取得最新 seq
        Long seq = 0L;//从数据库拉取 最大seq
        SysQywxChatdata paramSysQywxChatdata =  new SysQywxChatdata();
        paramSysQywxChatdata.setIsHandled(0L);
        List<SysQywxChatdata> sysQywxChatdataList = sysAIServiceImpl.sysQywxChatdataMapper.selectSysQywxChatdataListTop1(paramSysQywxChatdata);
        if(sysQywxChatdataList.size() > 0){
            seq = sysQywxChatdataList.get(0).getSeq();
        }
        System.out.println("待处理max seq:"+seq+" ...");

        if(seq.equals(0L)){
            System.out.println("无新消息需要处理  退出 ...");
            return;
        }

        //2. 先取得用户列表
        //夺取 今日日期 和 当夜日期
        //Date now = new Date();
        String today = DateFormatUtils.format(theDate, "yyyy-MM-dd");

        //临时测试 记得取消
        //today = "2024-08-07";///////////////////////////////////////////////

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Long beginMsgtime = (format.parse(today+" 00:00:00")).getTime();
        Long endMsgtime = (format.parse(today+" 23:59:59")).getTime();

        List<SysUser> userList = sysAIServiceImpl.userMapper.selectUserList(new SysUser());
        for (SysUser sysUser:userList) {
            //获取绑定的账户
            String BindUser = sysUser.getRemark();
            if(BindUser.length() <= 0){
                //未绑定 跳过
                System.out.println(sysUser.getUserName() + " 未绑定企业微信账户 跳过...");
            }else{
                System.out.println(sysUser.getUserName() + " 绑定企业微信账户【"+BindUser+"】 开始拉取数据...");

                long groupId = Long.parseLong(DateFormatUtils.format(theDate, "yyyyMMddHHmmssSS"));

                Map<String, Object> params =  new HashMap<String, Object>();
                params.put("beginMsgtime", beginMsgtime);
                params.put("endMsgtime", endMsgtime);

                //先清理当日 已创建任务
                //无需清理了！！！
                /*
                SysAiTasks sysAiTasks = new SysAiTasks();
                sysAiTasks.setIsEdit(0);
                sysAiTasks.setTaskOwner(BindUser);//注意 所有者！！！
                sysAiTasks.setParams(params);
                List<SysAiTasks> tmpSysAiTasksList = sysAIServiceImpl.sysAiTasksMapper.selectSysAiTasksList(sysAiTasks);
                for (SysAiTasks tmpSysAiTasks:tmpSysAiTasksList) {
                    sysAIServiceImpl.sysAiTasksMapper.deleteSysAiTasksById(tmpSysAiTasks.getId());
                }*/

                //再查询当日待处理信息
                paramSysQywxChatdata =  new SysQywxChatdata();
                paramSysQywxChatdata.setDecryptChatMsg(BindUser);
                paramSysQywxChatdata.setParams(params);
                paramSysQywxChatdata.setSeq(seq);
                sysQywxChatdataList = sysAIServiceImpl.sysQywxChatdataMapper.selectSysQywxChatdataList(paramSysQywxChatdata);

                sysQywxChatdataList.sort(Comparator.comparing(SysQywxChatdata::getSeq));//升序  从日期早的 聊天记录开始
                log.info("==========taskListHandled===========");

                if(sysQywxChatdataList.size() <= 0){
                    System.out.println("【"+BindUser+"】无新消息需要处理  下一位 ...");
                    continue;
                }

                //开始组合内容
                List<QYWXChatUni> QYWXChatUniList = new ArrayList<>();

                for (SysQywxChatdata sysQywxChatdata:sysQywxChatdataList) {

                    if(SysAIServiceImpl.checkAndInsertToday(QYWXChatUniList, sysQywxChatdata, BindUser)){
                        //成功加入列表
                    }else{
                        //失败
                    }
                }

                JSONArray sb = new JSONArray();
                int taskIndex = 0;

                for(int s=0;s<QYWXChatUniList.size();s++){
                    QYWXChatUni tmpChatUni = QYWXChatUniList.get(s);
                    log.info("handle QYWXChatUniList " + s + "/" + QYWXChatUniList.size());

                    if(!tmpChatUni.getIsdel()) {
                        //处理语义
                        //第一步 先把任务分割
                        List<SysAiTasks> splitSysAiTasksList = new ArrayList<>();
                        try {
                            if(tmpChatUni.getAllMsg().length() < 10){
                                System.out.println("聊天内容少于10个字....... 跳过");
                                //聊天内容少于10个字  就跳过吧
                                continue;
                            }
                            splitSysAiTasksList = SysAIServiceImpl.taskSplitContent(tmpChatUni.getAllMsg());
                        }catch (Exception ex){

                            try {
                                splitSysAiTasksList = SysAIServiceImpl.taskSplitContent(tmpChatUni.getAllMsg());
                            }catch (Exception ex2){
                                //二次失败 直接退出，等待重来
                                //todo 下次搞个 while true
                                return;
                            }

                        }

                        for (SysAiTasks splitSysAiTasks: splitSysAiTasksList) {
                            if(splitSysAiTasks.getTaskDetail().length() < 10){
                                System.out.println("聊天内容少于10个字....... 跳过");
                                //聊天内容少于10个字  就跳过吧
                                continue;
                            }
                            //开始大模型分析...
                            try {
                                int i = 0;
                                List<SysAiTasks> sysAiTasksList = SysAIServiceImpl.taskAnalysisContent(splitSysAiTasks.getTaskDetail(), tmpChatUni.getLastMsgtime());
                                System.out.println("from:" + tmpChatUni.getFrom());
                                System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTasksList));
                                for (int x = 0; x < sysAiTasksList.size(); x++) {
                                    //sysAiTasksList.forEach(task -> {
                                    SysAiTasks task = sysAiTasksList.get(x);
                                    //if(!"".equals(task.getTaskMemo()) && !"无".equals(task.getTaskMemo()) && task.getTaskMemo()!=null){
                                    //    if(!"".equals(task.getTaskDate()) && !"无".equals(task.getTaskDate()) && task.getTaskDate()!=null){

                                    if(task.getTaskMemo().equals("无")||task.getTaskMemo().equals("")){
                                        //不推送
                                    }else {
                                        taskIndex++;
                                        JSONObject jsonTask = new JSONObject();
                                        jsonTask.put("keyname",String.valueOf(taskIndex));
                                        jsonTask.put("value",String.valueOf(task.getTaskMemo()));
                                        sb.add(jsonTask);
                                        //sb.append(taskIndex + "." + task.getTaskMemo() + "\n");
                                    }

                                    task.setTaskOwner(BindUser);//注意 所有者！！
                                    task.setTaskCreator(tmpChatUni.getFrom());
                                    task.setRoomid(tmpChatUni.getRoomid());
                                    task.setRoomName(tmpChatUni.getRoomName());
                                    task.setMsgtime(tmpChatUni.getLastMsgtime());
                                    task.setGroupId(groupId);
                                    //task.setOrignalContent(tmpChatUni.getAllMsg());
                                    task.setOrignalContent( splitSysAiTasks.getTaskDetail());
                                    //task.setOrignalMsg(tmpChatUni.getQywxChatlist().get(0).getDecryptChatMsg());//暂时只存第一个 反正用来搜索发送人 和 收信人
                                    //以后通过 owner查询了  用来保存所有对话吧
                                    task.setOrignalMsg(tmpChatUni.getAllMsg());


                                    System.out.println("task=======" + JSON.toJSONString(task));

                                    if(task.getTaskMemo().equals("无")||task.getTaskMemo().equals("")){
                                        //不推送
                                    }else {
                                        //判断张三李四
                                        if(!StringUtils.isEmpty(task.getTaskMemo())&&task.getTaskMemo().indexOf("张三") > 0){

                                        }else {
                                            sysAIServiceImpl.sysAiTasksMapper.insertSysAiTasks(task);
                                        }
                                        try {
                                            //暂时不加入日历
                                            //SysAIServiceImpl.addQYWXSchedulePre(task);//加入日历
                                        } catch (Exception ex) {
                                            System.out.println("addQYWXSchedulePre=error======" + JSON.toJSONString(ex));
                                        }

                                        i = i + 1;
                                    }


                                /*    }else{
                                        System.out.println("SysAiTasks err 没有具体日期 跳过");
                                    }
                                }else{
                                    System.out.println("SysAiTasks err 没有任务内容 跳过");
                                }*/
                                    //});
                                }
                                System.out.println("AtomicInteger i 成功插入任务数: " + i);
                                if (i <= 0) {
                                    System.out.println("一个都没录入重来....... " + i);
                                    if(splitSysAiTasks.getTaskDetail().length() < 10){
                                        System.out.println("聊天内容少于10个字....... 跳过");
                                        //聊天内容少于10个字  就跳过吧
                                        continue;
                                    }
                                    //一个都没录入重来
                                    sysAiTasksList = SysAIServiceImpl.taskAnalysisContent(splitSysAiTasks.getTaskDetail(), tmpChatUni.getLastMsgtime());
                                    System.out.println("from:" + tmpChatUni.getFrom());
                                    System.out.println("sysAiTasksList=======" + JSON.toJSONString(sysAiTasksList));
                                    for (int x = 0; x < sysAiTasksList.size(); x++) {
                                        //sysAiTasksList.forEach(task -> {
                                        SysAiTasks task = sysAiTasksList.get(x);
                                        //if(!"".equals(task.getTaskMemo()) && !"无".equals(task.getTaskMemo()) && task.getTaskMemo()!=null){
                                        //if(!"".equals(task.getTaskDate()) && !"无".equals(task.getTaskDate()) && task.getTaskDate()!=null){

                                        if(task.getTaskMemo().equals("无")||task.getTaskMemo().equals("")){
                                            //不推送
                                        }else {
                                            taskIndex++;
                                            JSONObject jsonTask = new JSONObject();
                                            jsonTask.put("keyname",String.valueOf(taskIndex));
                                            jsonTask.put("value",String.valueOf(task.getTaskMemo()));
                                            sb.add(jsonTask);
                                            //sb.append(taskIndex + "." + task.getTaskMemo() + "\n");
                                        }
                                        task.setTaskOwner(BindUser);//注意 所有者！！
                                        task.setTaskCreator(tmpChatUni.getFrom());
                                        task.setRoomid(tmpChatUni.getRoomid());
                                        task.setRoomName(tmpChatUni.getRoomName());
                                        task.setMsgtime(tmpChatUni.getLastMsgtime());
                                        task.setGroupId(groupId);
                                        //task.setOrignalContent(tmpChatUni.getAllMsg());
                                        task.setOrignalContent( splitSysAiTasks.getTaskDetail());
                                        //task.setOrignalMsg(tmpChatUni.getQywxChatlist().get(0).getDecryptChatMsg());//暂时只存第一个 反正用来搜索发送人 和 收信人
                                        //以后通过 owner查询了  用来保存所有对话吧
                                        task.setOrignalMsg(tmpChatUni.getAllMsg());

                                        System.out.println("task=======" + JSON.toJSONString(task));
                                        //判断张三李四
                                        if(!StringUtils.isEmpty(task.getTaskMemo())&&task.getTaskMemo().indexOf("张三") > 0){

                                        }else {
                                            sysAIServiceImpl.sysAiTasksMapper.insertSysAiTasks(task);
                                        }

                                        try {
                                            //暂不加入日历
                                            //SysAIServiceImpl.addQYWXSchedulePre(task);//加入日历
                                        }catch (Exception ex){
                                            System.out.println("addQYWXSchedulePre=error======" + JSON.toJSONString(ex));
                                        }

                                    /*    }else{
                                            System.out.println("SysAiTasks err 没有具体日期 跳过");
                                        }
                                    }else{
                                        System.out.println("SysAiTasks err 没有任务内容 跳过");
                                    }*/
                                        //});
                                    }
                                    System.out.println("AtomicInteger i 成功插入任务数: " + i);
                                }

                            } catch (Exception ex) {
                                System.out.println("taskAnalysis err " + ex.toString());
                            }

                        }
                    }

                }

                if(sb.size()<=0 || sb.toString().equals("无")||sb.toString().equals("")){
                    //不推送
                }else {
                    //给客户推送消息
                    //倒叙插入任务列表
                    JSONArray message = new JSONArray();
                    int count = 0;
                    for(int i=(sb.size()-1);i>=0;i--){
                        JSONObject jsonTask = new JSONObject();
                        jsonTask.put("keyname",String.valueOf(count+1));
                        String content = ((JSONObject)sb.get(i)).get("value").toString();
                        if(content.length() > 28){
                            content = content.substring(0,25) + "...";
                        }
                        jsonTask.put("value", content);

                        message.add(jsonTask);
                        count++;
                        if(count>= 6){//不能超过6组
                            break;
                        }
                    }

                    /*/获取一个最新id
                    SysAiTasks newSysAiTasks = new SysAiTasks();
                    newSysAiTasks.setTaskOwner(BindUser);
                    Map<String, Object> params2 =  new HashMap<String, Object>();
                    params2.put("pageNum", 1);
                    params2.put("pageSize", 10);
                    newSysAiTasks.setParams(params2);
                    List<SysAiTasks>  sysAiTasksList = sysAIServiceImpl.sysAiTasksMapper.selectSysAiTasksList(newSysAiTasks);
                    */
                    //String lastId = "0";
                    /*
                    if(sysAiTasksList.size()>0){
                        lastId = sysAiTasksList.get(0).getId().toString();
                    }*/

                    String access_token = SysAIServiceImpl.getQYWXAccessToken();
                    sysAIServiceImpl.sendQYWXMessage(message, access_token, BindUser, String.valueOf(groupId));
                }

            }

        }

        //之前 都更新为 已处理
        //标记已处理.......
        paramSysQywxChatdata =  new SysQywxChatdata();
        paramSysQywxChatdata.setIsHandled(0L);
        paramSysQywxChatdata.setSeq(seq);
        sysQywxChatdataList = sysAIServiceImpl.sysQywxChatdataMapper.selectSysQywxChatdataList(paramSysQywxChatdata);

        for (SysQywxChatdata tmpQywxChatdata:sysQywxChatdataList) {
            SysQywxChatdata updateChatdata = new SysQywxChatdata();
            updateChatdata.setSeq(tmpQywxChatdata.getSeq());
            updateChatdata.setIsHandled(1L);

            sysAIServiceImpl.sysQywxChatdataMapper.updateSysQywxChatdata(updateChatdata);
        }
    }

    //当天所有内容 合并到旧列表中--- 组合内容时间   获取群名字  用户名字
    public static boolean checkAndInsertToday(List<QYWXChatUni> QYWXChatUniList, SysQywxChatdata tmpChatdata, String BindUser) throws IOException {
        JSONObject jsonChatdata = JSON.parseObject(tmpChatdata.getDecryptChatMsg());
        String roomid = jsonChatdata.getString("roomid");
        String roomName = "";
        String fromName = "";
        if(roomid.length() > 5){
            roomName = SysAIServiceImpl.getRoomName(roomid);
        }
        String from = jsonChatdata.getString("from");
        long msgtime = (new Date()).getTime();
        try{
            msgtime = jsonChatdata.getLong("msgtime");
        }catch (Exception ex){
            try{
                msgtime = jsonChatdata.getLong("time");
                roomid = "";
                from = jsonChatdata.getString("user");
            }catch (Exception ex1){

            }
        }

        if(!StringUtils.isEmpty(from) && !from.equals(BindUser) && roomName.equals("")){
            try {
                roomName = SysAIServiceImpl.getUserName(from);
            }catch (Exception ex2){

            }
        }

        try {
            fromName = SysAIServiceImpl.getUserName(from);
        }catch (Exception ex2){

        }

        String objcontent = "";
        try {
            JSONObject objectContent = jsonChatdata.getJSONObject("text");
            objcontent = SysAIServiceImpl.getUserName(from) + "：" + objectContent.getString("content");
        }catch (Exception ex){

        }
        //测试-测试-测试-测试-测试-测试-测试-
        //Timestamp timestamp = new Timestamp(msgtime);
        //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String formattedDate = formatter.format( new Date(timestamp.getTime()));
        //objcontent = formattedDate+": "+objcontent;
        //测试-测试-测试-测试-测试-测试-测试-

        JSONArray tolist = new JSONArray();
        try {
            tolist = jsonChatdata.getJSONArray("tolist");
            if(tolist.size()==1){
                String toto = tolist.get(0).toString();
                if(!toto.equals(BindUser) && roomName.equals("")){
                    roomName = SysAIServiceImpl.getUserName(toto);
                }
            }
        }catch (Exception ex){
            tolist.add("");
        }
        if(tolist == null || tolist.size()<=0){
            tolist = new JSONArray();
            tolist.add("");
        }

        for(int i=0;i<QYWXChatUniList.size();i++){
            //for(QYWXChatUni tmpChatUni:QYWXChatUniList){
            QYWXChatUni tmpChatUni = QYWXChatUniList.get(i);
            List<SysQywxChatdata> qywxChatlist = tmpChatUni.getQywxChatlist();
            String allMsg = tmpChatUni.getAllMsg();
            if(fromName!=""){//把我 替换成 发言人名称
                allMsg = allMsg.replaceAll("我",fromName);
            }
            //jsonChatdata.getString("roomid")

            if(roomid.equals("")||roomid==""){//一对一沟通时
                if (from.equals(tmpChatUni.getFrom())) {//如果发送人也匹配到了
                    log.info(tmpChatUni.getTolist().get(0).toString());
                    log.info(tolist.get(0).toString());
                    if(tmpChatUni.getTolist().get(0).toString().equals(tolist.get(0).toString())){//收信人也匹配到了
                        //符合条件了 加入队列
                        tmpChatUni.setLastMsgtime(msgtime);
                        qywxChatlist.add(tmpChatdata);
                        tmpChatUni.setQywxChatlist(qywxChatlist);

                        allMsg = allMsg + objcontent + "。\n";
                        tmpChatUni.setAllMsg(allMsg);

                        return true;
                    }
                }
                //反过来匹配也可以  发送人 就是 收件人。 收件人是发送人
                if (from.equals(tolist.get(0).toString())) {//如果发送人也匹配到了
                    log.info(tmpChatUni.getTolist().get(0).toString());
                    log.info(tolist.get(0).toString());
                    if(tmpChatUni.getTolist().get(0).toString().equals(tmpChatUni.getFrom())){//收信人也匹配到了
                        //符合条件了 加入队列
                        tmpChatUni.setLastMsgtime(msgtime);
                        qywxChatlist.add(tmpChatdata);
                        tmpChatUni.setQywxChatlist(qywxChatlist);

                        allMsg = allMsg + objcontent + "。\n";
                        tmpChatUni.setAllMsg(allMsg);

                        return true;
                    }
                }

            }else{//群聊中  群聊大合并
                if(roomid.equals(tmpChatUni.getRoomid())) {//如果群聊匹配到了
                    //符合条件了 加入队列
                    tmpChatUni.setLastMsgtime(msgtime);
                    qywxChatlist.add(tmpChatdata);
                    tmpChatUni.setQywxChatlist(qywxChatlist);

                    allMsg = allMsg + objcontent + "。\n";
                    tmpChatUni.setAllMsg(allMsg);

                    return true;
                }
            }
        }

        //插入失败  新增新段
        QYWXChatUni tmpChatUni = new QYWXChatUni();
        tmpChatUni.setFrom(from);
        tmpChatUni.setLastMsgtime(msgtime);
        tmpChatUni.setRoomid(roomid);
        tmpChatUni.setRoomName(roomName);
        tmpChatUni.setTolist(tolist);
        tmpChatUni.setAllMsg(objcontent + "。\n");
        tmpChatUni.setIsdel(false);

        List<SysQywxChatdata> qywxChatlist = new ArrayList<>();
        qywxChatlist.add(tmpChatdata);
        tmpChatUni.setQywxChatlist(qywxChatlist);

        QYWXChatUniList.add(tmpChatUni);

        return false;
    }


    //获取群名称
    public static String getRoomName(String roomId) throws IOException {
        String roomName = "获取失败";
        if(SysAIServiceImpl.roomNameList.containsKey(roomId)){
            return SysAIServiceImpl.roomNameList.get(roomId);
        }else{
            try {
                String access_token = SysAIServiceImpl.getQYWXAccessToken();
                JSONObject jsonResult = SysAIServiceImpl.getQYWXGroupChat(roomId, access_token);
                //把群聊名称拿到  并 拿到所有 用户名称
                //先获取群名
                JSONObject group_chat = jsonResult.getJSONObject("group_chat");
                roomName = group_chat.getString("name");
                if(SysAIServiceImpl.roomNameList.containsKey(roomId)){

                }else{
                    SysAIServiceImpl.roomNameList.put(roomId, roomName);
                }

                //开始获取 所有用户名
                JSONArray member_list =  group_chat.getJSONArray("member_list");
                for (Object obj : member_list) {
                    JSONObject member = (JSONObject) obj;
                    if(SysAIServiceImpl.userNameList.containsKey(member.getString("userid"))){

                    }else{
                        SysAIServiceImpl.userNameList.put(member.getString("userid"), member.getString("name"));
                    }
                }

            }catch (Exception ex){

            }
        }

        return roomName;
    }

    //获取用户名称
    public static String getUserName(String userid) throws IOException {
        String userName = "无名氏";
        if(SysAIServiceImpl.userNameList.containsKey(userid)){
            return SysAIServiceImpl.userNameList.get(userid);
        }else{
            try {
                String access_token = SysAIServiceImpl.getQYWXAccessToken();
                JSONObject jsonResult = SysAIServiceImpl.getQYWXContact(userid, access_token);
                //把群聊名称拿到  并 拿到所有 用户名称
                //先获取群名
                JSONObject external_contact = jsonResult.getJSONObject("external_contact");
                userName = external_contact.getString("name");
                if(SysAIServiceImpl.userNameList.containsKey(userid)){

                }else{
                    SysAIServiceImpl.userNameList.put(userid, userName);
                }

            }catch (Exception ex){

            }
        }
        return userName;
    }


    //获取企业微信access_token
    public static String getQYWXAccessToken() throws IOException {
        String access_token = "";
        String hostUrl= sysAIServiceImpl.qywxURL + "gettoken?corpid="+sysAIServiceImpl.corpID+"&corpsecret="+sysAIServiceImpl.secret;

        URL url = new URL(hostUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        connection.setDoOutput(false);// 禁止 URL 连接进行输出，默认为“false”
        connection.setDoInput(true);// 使用 URL 连接进行输入，默认为“true”
        connection.setUseCaches(false);// 忽略缓存
        connection.setConnectTimeout(60000);//连接超时
        connection.setReadTimeout(60000);//读取超时

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 打印结果
                System.out.println("Response Content: " + response.toString());
            }
        } else {
            System.out.println("POST error");
        }
        connection.disconnect();
        JSONObject jsonObject = JSONObject.parseObject(response.toString());

        access_token = jsonObject.getString("access_token");

        return access_token;
    }

    /*
    {
        "agentid": 1000002,
        "schedule": {
            -------"admins":["yaoleikaifa"],
            "start_time": 1719936626,
            "end_time": 1719946626,
            "is_whole_day":1,
            -----"attendees": [{"userid": "yaoleikaifa"}],
            ---"summary": "需求评审会议",
            ---"description": "2.0版本需求初步评审",
            "reminders": {
                "is_remind": 1,
                "remind_before_event_secs": 3600,
                "is_repeat": 1,
                "repeat_type": 7,
                "repeat_until": 1719946626,
                "is_custom_repeat": 1,
                "repeat_interval": 1,
                "timezone": 8
            },
            -----"location": "广州国际媒体港10楼1005会议室"
        }
    }
    */

    //企业微信前置
    public static void addQYWXSchedulePre(SysAiTasks task) throws IOException, ParseException {
        //测试客户
        List<String> customers = new ArrayList<>();
        customers.add("yaoleikaifa");
        customers.add("zhangliang");
        //测试结束

        //目标创建者
        List<String> useridList = new ArrayList<>();

        /*///测试数据
        task.setTaskMemo("今晚九点开个会，老姚和老张一起参加。");
        task.setTaskDetail("◆开会讨论相关议题\n");
        task.setTaskDate("2024-07-03");
        task.setTaskTime("21:00:00");
        task.setTaskAddress("芜湖");
        task.setOrignalMsg("{\"msgid\":\"17507798674328129522_1719913711297_external\",\"action\":\"send\",\"from\":\"wm4EHiUAAAJS6XMwMQ-Au2NDmixKjvQA\",\"tolist\":[\"wm4EHiUAAAsLTzPK-0I3WY4graZdS0jg\",\"wm4EHiUAAAmi_jByCtmVf6eHdm0Op7rQ\",\"wm4EHiUAAAqDgcBtL0Lme6PFUwg2wxlw\",\"wm4EHiUAAAoC2As0qSNXcsHQvmBFxi2A\",\"wm4EHiUAAAK9mMGrnlKi_uid9rh-iNrw\",\"zhangliang\",\"yaoleikaifa\"],\"roomid\":\"wr4EHiUAAATeLfHYbnWi8CqMFTGj0mIg\",\"msgtime\":1719913707588,\"msgtype\":\"text\",\"text\":{\"content\":\"不用复原\"}}");
        /// *///测试数据结束

        String orignalMsg = task.getOrignalMsg();
        for(String customer:customers){
            if(orignalMsg.indexOf(customer) > 0){
                useridList.add(customer);
            }
        }
        String access_token = SysAIServiceImpl.getQYWXAccessToken();
        //所有客户 创建一遍日程
        for(String userid:useridList){
            sysAIServiceImpl.addQYWXSchedule(task, access_token, userid);
        }
    }

    //添加日历
    public static void addQYWXSchedule(SysAiTasks task,String access_token, String userid) throws IOException, ParseException {

        String hostUrl = sysAIServiceImpl.qywxURL + "oa/schedule/add?access_token="+access_token;

        ///////组合json 对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("agentid", sysAIServiceImpl.agentId);

        JSONObject scheduleJSON = new JSONObject();//主计划
        scheduleJSON.put("location", task.getTaskAddress());
        scheduleJSON.put("summary", task.getTaskMemo());
        scheduleJSON.put("description", splitJson(task.getTaskDetail()));

        //admins
        JSONArray admins = new JSONArray();
        admins.add(userid);
        scheduleJSON.put("admins", admins);
        //attendees
        JSONArray attendees = new JSONArray();
        JSONObject useridJSON = new JSONObject();
        useridJSON.put("userid",userid);
        attendees.add(useridJSON);
        scheduleJSON.put("attendees", attendees);

        //日期处理
        Timestamp start_time = new Timestamp((new Date()).getTime());

        String taskDate = task.getTaskDate();
        String taskTime = task.getTaskTime();
        if(taskDate!=null && taskDate.indexOf("-") > 0) {
            if (taskTime != null && taskTime.indexOf(":") > 0) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                start_time = new Timestamp((format.parse(taskDate+" "+taskTime)).getTime());

                JSONObject reminders = new JSONObject();
                reminders.put("is_remind", 1);
                reminders.put("remind_before_event_secs", 3600);
                reminders.put("is_repeat", 1);
                reminders.put("repeat_type", 7);
                reminders.put("repeat_until", start_time.getTime()/1000L + 3600L);
                reminders.put("is_custom_repeat", 1);
                reminders.put("repeat_interval", 1);
                reminders.put("timezone", 8);

                scheduleJSON.put("reminders", reminders);
                scheduleJSON.put("is_whole_day", 0);
            }else{
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                start_time = new Timestamp((format.parse(taskDate)).getTime());
                scheduleJSON.put("is_whole_day", 1);
            }
        }else{
            scheduleJSON.put("is_whole_day", 1);
        }

        scheduleJSON.put("start_time", start_time.getTime()/1000L);
        scheduleJSON.put("end_time", start_time.getTime()/1000L + 3600L);

        jsonObject.put("schedule", scheduleJSON);

        String json = jsonObject.toJSONString();
        System.out.println("======json========" + json);
        /////////////////组合完毕


        URL url = new URL(hostUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        connection.setDoOutput(true);
        connection.setConnectTimeout(60000);//连接超时
        connection.setReadTimeout(60000);//读取超时

        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(json.getBytes());
        outputStream.flush();

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 打印结果
                System.out.println("Response Content: " + response.toString());
            }
        } else {
            System.out.println("POST error");
        }

        connection.disconnect();


    }

    //获取群名称
    public static JSONObject getQYWXGroupChat(String roomId,String access_token) throws IOException, ParseException {

        String hostUrl = sysAIServiceImpl.qywxURL + "externalcontact/groupchat/get?access_token="+access_token;

        ///////组合json 对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("chat_id", roomId);
        jsonObject.put("need_name", 1);

        String json = jsonObject.toJSONString();
        System.out.println("======json========" + json);
        /////////////////组合完毕


        URL url = new URL(hostUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        connection.setDoOutput(true);
        connection.setConnectTimeout(60000);//连接超时
        connection.setReadTimeout(60000);//读取超时

        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(json.getBytes());
        outputStream.flush();

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 打印结果
                System.out.println("Response Content: " + response.toString());
            }
        } else {
            System.out.println("POST error");
        }

        connection.disconnect();

        JSONObject jsonResult = JSONObject.parseObject(response.toString());
        return jsonResult;
    }

    //获取客户名称
    public static JSONObject getQYWXContact(String userid,String access_token) throws IOException, ParseException {

        String hostUrl = sysAIServiceImpl.qywxURL + "externalcontact/get?access_token="+access_token+"&external_userid="+userid+"&cursor=CURSOR";

        URL url = new URL(hostUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        connection.setDoOutput(false);// 禁止 URL 连接进行输出，默认为“false”
        connection.setDoInput(true);// 使用 URL 连接进行输入，默认为“true”
        connection.setUseCaches(false);// 忽略缓存
        connection.setConnectTimeout(60000);//连接超时
        connection.setReadTimeout(60000);//读取超时

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 打印结果
                System.out.println("Response Content: " + response.toString());
            }
        } else {
            System.out.println("POST error");
        }
        connection.disconnect();
        JSONObject jsonResult = JSONObject.parseObject(response.toString());
        return jsonResult;
    }


    //推送消息
    public static void sendQYWXMessage(JSONArray message, String access_token, String userid, String groupId) throws IOException, ParseException {

        String hostUrl = sysAIServiceImpl.qywxURL + "message/send?access_token="+access_token;

        //测试测试
        //userid = "yaoleikaifa";

        ///////组合json 对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", userid);
        jsonObject.put("msgtype", "template_card");
        jsonObject.put("agentid", sysAIServiceImpl.agentId);
        jsonObject.put("enable_id_trans", 0);
        jsonObject.put("enable_duplicate_check", 0);
        jsonObject.put("duplicate_check_interval", 1800);


        JSONObject mainJSON = new JSONObject();//主计划
        mainJSON.put("card_type", "button_interaction");

        Date now = new Date();
        String today = DateFormatUtils.format(now, "MM月dd日HH时");

        JSONObject titleJSON = new JSONObject();
        titleJSON.put("title",today+" 会话总结已生成");
        mainJSON.put("main_title", titleJSON);

        JSONObject quoteAreaObject = new JSONObject();
        quoteAreaObject.put("type", 0);
        quoteAreaObject.put("quote_text", message);
        //mainJSON.put("quote_area", quoteAreaObject);

        mainJSON.put("horizontal_content_list", message);
        mainJSON.put("task_id", userid+DateFormatUtils.format(now, "yyyyMMddHHmmss"));

        JSONArray button_list = new JSONArray();

        //JSONObject btn1 = new JSONObject();///此按钮 取消！！！
        //btn1.put("text", "详情");
        //btn1.put("style", 1);
        //btn1.put("type", 1);
        //btn1.put("url", "http://aiuser.icemz.com/#/pages/ai/detail?taskOwner="+userid+"&id="+taskid);
        //button_list.add(btn1);

        JSONObject btn2 = new JSONObject();
        btn2.put("text", "查看更多");
        btn2.put("style", 1);
        btn2.put("type", 1);
        btn2.put("url", "http://aiuser.icemz.com/#/pages/ai/list?taskOwner="+userid+"&groupId="+groupId+"&id="+DateFormatUtils.format(now, "yyyyMMddHHmmss"));
        button_list.add(btn2);

        mainJSON.put("button_list",button_list);

        jsonObject.put("template_card", mainJSON);

        String json = jsonObject.toJSONString();
        System.out.println("======json========" + json);
        /////////////////组合完毕


        URL url = new URL(hostUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
        connection.setDoOutput(true);
        connection.setConnectTimeout(60000);//连接超时
        connection.setReadTimeout(60000);//读取超时

        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(json.getBytes());
        outputStream.flush();

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        StringBuilder response = new StringBuilder();

        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
            try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                // 打印结果
                System.out.println("Response Content: " + response.toString());
            }
        } else {
            System.out.println("POST error");
        }

        connection.disconnect();

    }

    public static String splitJson(String content){
        //content = "[{\"行动项\":\"参加产品会\"}]";
        String result = "";
        try {
            JSONArray jsonArray = JSONArray.parseArray(content);
            for (int i=0;i<jsonArray.size();i++){
                try {
                    JSONObject jsonChatdata = JSONObject.parseObject(jsonArray.get(i).toString());
                    result = result + "◆" + jsonChatdata.getString("行动项") + "\n";
                }catch (Exception ex3){
                    result = result + "◆" + jsonArray.get(i).toString() + "\n";
                }
            }

        }catch (Exception ex1){

            try {
                JSONObject jsonChatdata = JSONObject.parseObject(content);
                result = result + "◆" + jsonChatdata.getString("行动项") + "\n";

            }catch (Exception ex2) {
                result = content;
            }
        }

        return result;
    }

    //先检验 是否可以合并到旧列表中
    public static boolean checkAndInsert(List<QYWXChatUni> QYWXChatUniList, SysQywxChatdata tmpChatdata) throws IOException {
        JSONObject jsonChatdata = JSON.parseObject(tmpChatdata.getDecryptChatMsg());
        String roomid = jsonChatdata.getString("roomid");
        String roomName = "";
        if(roomid.length() > 5){
            roomName = SysAIServiceImpl.getRoomName(roomid);
        }
        String from = jsonChatdata.getString("from");
        long msgtime = (new Date()).getTime();
        try{
            msgtime = jsonChatdata.getLong("msgtime");
        }catch (Exception ex){
            try{
                msgtime = jsonChatdata.getLong("time");
                roomid = "";
                from = jsonChatdata.getString("user");
            }catch (Exception ex1){

            }
        }
        String objcontent = "";
        try {
            JSONObject objectContent = jsonChatdata.getJSONObject("text");
            objcontent = SysAIServiceImpl.getUserName(from) + "：" + objectContent.getString("content");
        }catch (Exception ex){

        }
        //测试-测试-测试-测试-测试-测试-测试-
        //Timestamp timestamp = new Timestamp(msgtime);
        //SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String formattedDate = formatter.format( new Date(timestamp.getTime()));
        //objcontent = formattedDate+": "+objcontent;
        //测试-测试-测试-测试-测试-测试-测试-

        JSONArray tolist = new JSONArray();
        try {
            tolist = jsonChatdata.getJSONArray("tolist");
        }catch (Exception ex){
            tolist.add("");
        }
        if(tolist == null || tolist.size()<=0){
            tolist = new JSONArray();
            tolist.add("");
        }

        for(int i=0;i<QYWXChatUniList.size();i++){
        //for(QYWXChatUni tmpChatUni:QYWXChatUniList){
            QYWXChatUni tmpChatUni = QYWXChatUniList.get(i);
            List<SysQywxChatdata> qywxChatlist = tmpChatUni.getQywxChatlist();
            String allMsg = tmpChatUni.getAllMsg();
            //jsonChatdata.getString("roomid")

            if(roomid.equals("")||roomid==""){//一对一沟通时
                if(roomid.equals(tmpChatUni.getRoomid())) {//如果群聊匹配到了 空值
                    if (from.equals(tmpChatUni.getFrom())) {//如果发送人也匹配到了
                        log.info(tmpChatUni.getTolist().get(0).toString());
                        log.info(tolist.get(0).toString());
                        if(tmpChatUni.getTolist().get(0).toString().equals(tolist.get(0).toString())){//收信人也匹配到了
                            long lastMsgtime = tmpChatUni.getLastMsgtime();
                            if(Math.abs(msgtime - lastMsgtime) <= SysAIServiceImpl.delayTimestamp){
                                //符合条件了 加入队列
                                tmpChatUni.setLastMsgtime(msgtime);
                                qywxChatlist.add(tmpChatdata);
                                tmpChatUni.setQywxChatlist(qywxChatlist);

                                allMsg = allMsg + objcontent + "。\n";
                                tmpChatUni.setAllMsg(allMsg);

                                return true;
                            }
                        }
                    }
                }
            }else{//群聊中
                if(roomid.equals(tmpChatUni.getRoomid())) {//如果群聊匹配到了
                    if(from.equals(tmpChatUni.getFrom())){//如果发送人也匹配到了
                        long lastMsgtime = tmpChatUni.getLastMsgtime();
                        if(Math.abs(msgtime - lastMsgtime) <= SysAIServiceImpl.delayTimestamp){
                            //符合条件了 加入队列
                            tmpChatUni.setLastMsgtime(msgtime);
                            qywxChatlist.add(tmpChatdata);
                            tmpChatUni.setQywxChatlist(qywxChatlist);

                            allMsg = allMsg + objcontent + "。\n";
                            tmpChatUni.setAllMsg(allMsg);

                            return true;
                        }
                    }
                }
            }
        }

        //插入失败  新增新段
        QYWXChatUni tmpChatUni = new QYWXChatUni();
        tmpChatUni.setFrom(from);
        tmpChatUni.setLastMsgtime(msgtime);
        tmpChatUni.setRoomid(roomid);
        tmpChatUni.setRoomName(roomName);
        tmpChatUni.setTolist(tolist);
        tmpChatUni.setAllMsg(objcontent + "。\n");
        tmpChatUni.setIsdel(false);

        List<SysQywxChatdata> qywxChatlist = new ArrayList<>();
        qywxChatlist.add(tmpChatdata);
        tmpChatUni.setQywxChatlist(qywxChatlist);

        QYWXChatUniList.add(tmpChatUni);

        return false;
    }

    public static Date getDate(String text) {
        try {
            Pattern pattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");
            Matcher matcher = pattern.matcher(text);
            while (matcher.find()) {
                String date = matcher.group();
                //System.out.println(date);
                return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse((date+" 9:00:00").toString().replace("T", " "));
            }
        }catch (Exception ex){
        }
        return null;
    }


    @Override
    public String chat(String content) throws Exception {

        String result = BigModelWeb.chat(content);

        //sysAITask.setTaskmemo(result);
        return result;
    }

}

//聊天内容组合体
class QYWXChatUni
{
    private Long lastMsgtime;

    private String from;

    private JSONArray tolist;

    private String roomid;

    private String roomName;

    private String allMsg;//所有合并消息

    private boolean isdel;

    private List<SysQywxChatdata> qywxChatlist;

    public QYWXChatUni()
    {

    }


    public Long getLastMsgtime()
    {
        return lastMsgtime;
    }

    public void setLastMsgtime(Long lastMsgtime)
    {
        this.lastMsgtime = lastMsgtime;
    }

    public String getFrom()
    {
        return from;
    }

    public void setFrom(String from)
    {
        this.from = from;
    }

    public JSONArray getTolist()
    {
        return tolist;
    }

    public void setTolist(JSONArray tolist)
    {
        this.tolist = tolist;
    }

    public String getRoomid()
    {
        return roomid;
    }

    public void setRoomid(String roomid)
    {
        this.roomid = roomid;
    }

    public String getRoomName()
    {
        return roomName;
    }

    public void setRoomName(String roomName)
    {
        this.roomName = roomName;
    }

    public List<SysQywxChatdata> getQywxChatlist()
    {
        return qywxChatlist;
    }

    public void setQywxChatlist(List<SysQywxChatdata> qywxChatlist)
    {
        this.qywxChatlist = qywxChatlist;
    }

    public String getAllMsg()
    {
        return allMsg;
    }

    public void setAllMsg(String allMsg)
    {
        this.allMsg = allMsg;
    }

    public boolean getIsdel()
    {
        return isdel;
    }

    public void setIsdel(boolean isdel)
    {
        this.isdel = isdel;
    }
}
